package com.jarvis.hospital.prescription;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.jarvis.hospital.R;
import com.jarvis.hospital.common.BaseFragment;
import com.jarvis.hospital.common.ResponseData;
import com.jarvis.hospital.login.model.LoginModel;
import com.jarvis.hospital.login.model.UserModel;
import com.jarvis.hospital.patient.adapter.MessageDetailAdapter;
import com.jarvis.hospital.patient.model.MessageListModel;
import com.jarvis.hospital.patient.model.MessageModel;
import com.jarvis.hospital.prescription.adapter.CommentAdapter;
import com.jarvis.hospital.prescription.adapter.PrescriptionTimeAdapter;
import com.jarvis.hospital.prescription.model.CommentListModel;
import com.jarvis.hospital.prescription.model.CommentModel;
import com.jarvis.hospital.prescription.model.EventBusModel;
import com.jarvis.hospital.prescription.model.PrescriptionDetailModel;
import com.jarvis.hospital.prescription.model.PrescriptionTimeDetailModel;
import com.jarvis.hospital.prescription.model.PrescriptionTimeModel;
import com.jarvis.hospital.servers.ApiService;
import com.jarvis.hospital.util.DividerItemDecoration;
import com.jarvis.hospital.util.SharePreferenceKey;
import com.jarvis.hospital.util.SharePreferenceUtils;
import com.jarvis.hospital.util.net.RequestApi;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import in.srain.cube.views.ptr.PtrClassicFrameLayout;
import in.srain.cube.views.ptr.PtrDefaultHandler2;
import in.srain.cube.views.ptr.PtrFrameLayout;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by jarvis.liu on 2016-11-02.
 */

public class CommentFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.recy_comment)
    RecyclerView recy_comment;
    @BindView(R.id.ptr_comment)
    PtrClassicFrameLayout ptr_comment;
    private CommentAdapter commentAdapter;
    private int pageSize = 10;
    private int currentPage = 1;
    private int maxPage = 1;
    @BindView(R.id.ed_value)
    EditText ed_value;
    @BindView(R.id.tv_send)
    TextView tv_send;
    private ApiService service;
    private String prescriptionId;
    private String commentType = "0";
    private String parentId;
    private String targetUserId = "";

    public static CommentFragment newInstance(String prescriptionId) {
        Bundle args = new Bundle();
        CommentFragment fragment = new CommentFragment();
        fragment.setArguments(args);
        fragment.prescriptionId = prescriptionId;
        fragment.parentId = prescriptionId;
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_comment;
    }

    @Override
    public void initData() {
        ptr_comment.postDelayed(
                new Runnable() {
                    @Override
                    public void run() {
                        ptr_comment.autoRefresh();
                    }
                }, 100);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            setStatus(true);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusModel model) {
        if (ed_value.getText().toString().isEmpty()) {
            commentType = "0";
            parentId = prescriptionId;
            targetUserId = "";
            ed_value.setHint("评论");
        }
        ptr_comment.requestFocus();
        ptr_comment.setFocusable(true);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        service = RequestApi.create(ApiService.class);
        setStatus(true);
        tv_send.setOnClickListener(this);
        setAdapter();
        setRefresh();
        recy_comment.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void SimpleOnItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                final CommentModel commentModel = commentAdapter.getData().get(i);
                        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
                 String userId = userModel.getUserId();
                if (userId.equals(commentModel.getOwnerUserId())) {
                    if (ed_value.getText().toString().isEmpty()) {
                        //删除评论
                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext())
                                .setTitle("温馨提示")
                                .setMessage("删除该条评论吗")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        deleteComment(commentModel.getCommentId());
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        dialogBuilder.create().show();
                    }
                } else {
                    if (ed_value.getText().toString().isEmpty()) {
                        ed_value.requestFocus();
                        ed_value.setFocusable(true);
                        ed_value.setHint("回复" + commentModel.getOwnerUserName());
                        commentType = "1";
                        parentId = commentModel.getCommentId();
                        targetUserId = commentModel.getOwnerUserId();
                    } else {
                        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext())
                                .setTitle("温馨提示")
                                .setMessage("回复" + commentModel.getOwnerUserName())
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        ed_value.requestFocus();
                                        ed_value.setFocusable(true);
                                        ed_value.setText("");
                                        ed_value.setHint("回复" + commentModel.getOwnerUserName());
                                        commentType = "1";
                                        parentId = commentModel.getCommentId();
                                        targetUserId = commentModel.getOwnerUserId();
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                });

                        dialogBuilder.create().show();
                    }
                }
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 设置下拉刷新
     */
    public void setRefresh() {
        ptr_comment.setMode(PtrFrameLayout.Mode.LOAD_MORE);
        ptr_comment.disableWhenHorizontalMove(true);
        ptr_comment.setLastUpdateTimeRelateObject(this);
        ptr_comment.setPtrHandler(new PtrDefaultHandler2() {

            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                return PtrDefaultHandler2.checkContentCanBePulledUp(frame, recy_comment, footer);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler2.checkContentCanBePulledDown(frame, recy_comment, header);
            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                if (currentPage < maxPage) {
                    currentPage++;
                    loadData();
                } else {
                    ptr_comment.refreshComplete();
                }
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                commentAdapter.setNewData(new ArrayList<CommentModel>());
                currentPage = 1;
                loadData();
            }
        });
    }

    /**
     * 设置adapter
     */
    public void setAdapter() {
        commentAdapter = new CommentAdapter(R.layout.item_comment, new ArrayList<CommentModel>());
        recy_comment.setLayoutManager(new LinearLayoutManager(getActivity()));
        recy_comment.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST, getResources().getDrawable(R.drawable.divier_order_gray)));
        commentAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_BOTTOM);
        recy_comment.setAdapter(commentAdapter);
    }

    private void deleteComment(String commentid) {
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        showDialog("加载中");
        service.delComment(commentid, userId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData messageListModelResponseData) {
                        if (messageListModelResponseData != null) {
                            int resultCode = messageListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                ptr_comment.postDelayed(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                ptr_comment.autoRefresh();
                                            }
                                        }, 100);
                            } else {
                                showTextToast(messageListModelResponseData.getMessage());
                            }
                            ed_value.setText("");
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void sendMessage() {
        String content = ed_value.getText().toString();
        if (TextUtils.isEmpty(content)) {
            showTextToast("不能发送空评论");
            return;
        }
        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
        String userId = userModel.getUserId();
        service.sendComment(userId, prescriptionId, commentType, parentId, content, targetUserId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData messageListModelResponseData) {
                        if (messageListModelResponseData != null) {
                            int resultCode = messageListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                commentType = "0";
                                parentId = prescriptionId;
                                targetUserId = "";
                                ed_value.setHint("评论");
                                ptr_comment.postDelayed(
                                        new Runnable() {
                                            @Override
                                            public void run() {
                                                ptr_comment.autoRefresh();
                                            }
                                        }, 100);
                            } else {
                                showTextToast(messageListModelResponseData.getMessage());
                            }
                            ed_value.setText("");
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        disMiss();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        disMiss();
                    }
                });
    }

    private void loadData() {
//        UserModel userModel = SharePreferenceUtils.getObject(SharePreferenceKey.LOGIN_MODEL, LoginModel.class).getUserInfo();
//        String userId = userModel.getUserId();
        service.getComment(currentPage, pageSize, prescriptionId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .safeSubscribe(new Observer<ResponseData<CommentListModel>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseData<CommentListModel> commentListModelResponseData) {
                        if (commentListModelResponseData != null) {
                            int resultCode = commentListModelResponseData.getResultCode();
                            if (resultCode == 200) {
                                int total_count = commentListModelResponseData.getTotalcount();
                                maxPage = total_count % pageSize == 0 ? total_count / pageSize : total_count / pageSize + 1;
                                commentAdapter.addData(commentListModelResponseData.getData().getCommentList());
                            } else {
                                showTextToast(commentListModelResponseData.getMessage());
                            }
                        } else {
                            showTextToast("请求失败");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ptr_comment.refreshComplete();
                        showTextToast(RequestApi.detailError(e));
                    }

                    @Override
                    public void onComplete() {
                        ptr_comment.refreshComplete();
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_send:
                sendMessage();
                break;
        }
    }
}
